# -*- coding:utf-8 -*-
from datetime import datetime

import torndb

import setting
from util.mail_sender import MailSender

class OnceCardInventory(object):

    """
    次卡库存报警监测，10分钟监测一次

    """

    def __init__(self):

        self.db = torndb.Connection(
            host=setting.mysql_host,
            database=setting.mysql_database,
            user=setting.mysql_user,
            password=setting.mysql_password,
            charset='utf8'
        )

        self.alarm_min_count = 10  # 小于10个报警，提示补库存

        self.mail = MailSender()

    def _get_product_inventory(self):
        return self.db.query("select p.title, (p.total-o.cnt) balanace "
                             "  from t_product p, (select op.product_id, sum(cnt) cnt from r_order_product op, (select id from t_order where status = 1) t where t.id = op.order_id and op.source in (0, 1) group by product_id) o "
                             " where o.product_id = p.id and p.del_flag=0 order by p.id ")

    def _get_code_count(self):
        code = self.db.get("select count(*) c from t_qrcode_for_oncecard where order_product_id = '' and status=0")
        return code.c

    def _alarm_notice(self, p):
        html = u"<font style='color:red;'>库存剩余:{}个, 请及时补充库存。</font>".format(p.balanace)
        subject = u'空铁管家 - 商品【{}】库存不足报警 数量剩余{}个'.format(p.title, p.balanace)

        if html:
            self.mail._send_mail(self.mail.receivers, subject, html)

    def runner(self):
        p = self._get_product_inventory()
        if p.balanace < self.alarm_min_count:
            self._alarm_notice(p)

if __name__ == '__main__':
    print "run start : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    oci = OnceCardInventory()
    oci.runner()
    oci.db.close()
    print "run end : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))